package com.example.toutiao.base
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.toutiao.mvp.presenter.BasePresenter
import com.example.toutiao.mvp.view.BaseView
import com.example.toutiao.ui.user.EvtMsgModel
import com.example.toutiao.utils.SharedPreferencesUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


abstract class BaseFragment <V, P : BasePresenter<V>>: Fragment(), BaseView {
    private var mPresenter: P? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
       val view=inflater.inflate(getLayoutId(), container, false)
        initView(view!!)

        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        /*如果视图不存在，则创建视图*/
        if (mPresenter == null) {
            mPresenter = createPresenter()
        }
        /*将视图传入适配器*/
        mPresenter!!.bindView(this as V)
        if(isRegister()){
            EventBus.getDefault().register(this)
            Log.e("event","create eventBus")
        }
        //加载数据
        initData()
    }


    fun startActivity(clz:Class<*>){
        startActivity(Intent(context,clz))
    }

    /**
    * 获取布局的id
    */
    protected abstract fun getLayoutId(): Int

    /**
     * 初始化 暂时不知道
     */
    protected abstract fun initView(view: View)

    /**
     * 初始化数据
     */
    protected abstract fun initData()

    /**
     * 为子类提供一个 抽象方法 创建适配器
     */
    protected abstract fun createPresenter(): P

    /**
     * 注册eventBus
     */
    protected abstract fun isRegister():Boolean

    /**
     * 子类通过这个方法获取父类的persenter 适配器
     */
    fun getPresenter() = mPresenter
    override fun onDestroy() {
        /*在适配器不为空的情况下解绑*/

        mPresenter!!.unBindView()
        /*解绑eventBus*/
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy()

    }


    /*event bus 接受消息的两种方法 普通消息 黏性消息*/

    /**
     * 普通消息 实时
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun getMessage(message: EvtMsgModel<*>){

    }

    /**
     * 黏性消息 存在延时
     */
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    open fun getMessageSticky(message: EvtMsgModel<*>){

    }

    /**
     * 发送消息
     */
    open fun postMsg(message: EvtMsgModel<*>){
        EventBus.getDefault().post(message)
    }

    /**
     * 获取token
     */
    fun getToken():String?=SharedPreferencesUtils.getSaveToken(requireActivity(),Constants.TOKEN)
    fun isTokenNotNull():Boolean=!TextUtils.isEmpty(getToken())

}